//
//  EMSellingWellViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 14/12/27.
//  Copyright (c) 2014年 cczu. All rights reserved.
//

#import "EMSellingWellViewController.h"
#import "UINavigationController+EMNavi.h"
#import "EMSellingWellViewController.h"
#import "EMSellingWellCell.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "EMGoodListReqBody.h"
#import "EMGoodListRespBody.h"
#import "AppDelegate.h"
#import "EMGoodInfo3.h"
#import "UIImageView+WebCache.h"
#import "EMDetailInfoViewController.h"
#import "UserInfo.h"
#import "EMLoginViewController.h"
#import "EMShoppingCartViewController.h"

@interface EMSellingWellViewController ()
{
    UITableView *sellingTable;
    AppDelegate *app;
    int page;
}
@end

@implementation EMSellingWellViewController
- (void)hideBottomBar
{
    for(UIView *view in self.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
            view.hidden = YES;
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self hideBottomBar];
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    self.view.backgroundColor = RGB(242, 242, 242);
    page = 1;
    self.goodList = [[NSMutableArray alloc] init];
    
    [self.navigationController setNavigationMode:EMNavigationModeDefault andSubMode:0];
    self.navigationItem.title = self.titleString;
    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 32);
    [button setImage:[UIImage imageNamed:@"button_导航_返回_白"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:button];
    
    button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 44, 44);
    [button setImage:[UIImage imageNamed:@"icon_详情_分享"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:button];
    [self getGoodInfo];
    
    UIButton *cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cartBtn setImage:[UIImage imageNamed:@"button_进入购物车"] forState:UIControlStateNormal];
    [cartBtn setFrame:CGRectMake(20, [UIScreen mainScreen].bounds.size.height - 49 - 30, 55, 55)];
    [cartBtn addTarget:self action:@selector(enterToCart:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cartBtn];
}
- (void)backAction: (UIButton *)sender
{
    self.navigationController.navigationBar.barTintColor = RGB(255, 255, 255);
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)headerPulledRefresh
{
    [self.goodList removeAllObjects];
    page = 1;
    [self getGoodInfo];
    [sellingTable reloadData];
    [sellingTable headerEndRefreshing];
}
- (void)footerPulledRefresh
{
    [self getGoodInfo];
    [sellingTable reloadData];
}

- (void)getGoodInfo
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMGoodListReqBody *reqBody = [[EMGoodListReqBody alloc] init];
    reqBody.JUDGEMETHOD = self.judgeMethod;
    reqBody.FLAG = self.judgeFlag;
    reqBody.GETTIMES = [NSString stringWithFormat:@"%d",page];
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMGoodListRespBody *respBody = [EMGoodListRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            NSMutableArray * arr = [respBody.GOODINFO mutableCopy];
            for (int i = 0; i< arr.count; i++) {
                [self.goodList addObject:arr[i]];
            }
            [sellingTable footerEndRefreshing];
            page ++;
        } else {
            [sellingTable footerEndRefreshing];
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor redColor];
    sellingTable = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    sellingTable.delegate = self;
    sellingTable.dataSource = self;
    [self.view addSubview:sellingTable];
    [sellingTable addFooterWithTarget:self action:@selector(footerPulledRefresh)];
    [sellingTable addHeaderWithTarget:self action:@selector(headerPulledRefresh)];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.goodList.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"sellingCell";
    EMSellingWellCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[EMSellingWellCell alloc] initWithFrame:CGRectZero];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    EMGoodInfo3 *info = [[EMGoodInfo3 alloc] initWithGoodInfo:self.goodList[indexPath.section]];
    cell.goodNameLabel.text = info.m_name;
    cell.goodDescLabel.text = (NSNull *)info.m_goodDesc == [NSNull null] ? @"" : info.m_goodDesc;
    cell.priceLabel.text = [NSString stringWithFormat:@"¥%.2f", [info.m_nowPrice floatValue]];
    if ([info.m_mode isEqualToString:@"0"]) {
        cell.originPriceLabel.hidden = YES;
    } else {
        NSMutableAttributedString *oPrice = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"¥%@", info.m_originPrice]];
        [oPrice addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, info.m_originPrice.length+1)];
        cell.originPriceLabel.attributedText = oPrice;
    }
    
    [cell.goodImageView sd_setImageWithURL:[NSURL URLWithString:info.m_imgUrl]];
    cell.addToCart.tag = 60000 + indexPath.section;
    [cell.addToCart addTarget:self action:@selector(addToCart:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (void)addToCart:(UIButton *)btn
{
    
    if ([UserInfo sharedUserInfo].m_isLogin) {
        EMGoodInfo3 *info = [[EMGoodInfo3 alloc] initWithGoodInfo:self.goodList[btn.tag - 60000]];
        [app addToCartWithID:info.m_id];
    } else {
        [app showTip:@"请先登录"];
        EMLoginViewController *controller = [[EMLoginViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
    
}
- (void)enterToCart:(UIButton *)sender
{
    if ([UserInfo sharedUserInfo].m_isLogin) {
        EMShoppingCartViewController *controller = [[EMShoppingCartViewController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    } else {
        [app showTip:@"请先登录"];
        EMLoginViewController *controller = [[EMLoginViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 88;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EMGoodInfo3 *info = [[EMGoodInfo3 alloc] initWithGoodInfo:self.goodList[indexPath.section]];
    EMDetailInfoViewController *controller = [[EMDetailInfoViewController alloc] init];
    controller.goodID = info.m_id;
    [self.navigationController pushViewController:controller animated:YES];
}
@end
